<template>
  <div>
    <div id="allmap"
         style="width: 100%;height: 500px;display:none;"></div>
    <div>
      <mt-header style="font-size:18px;position: sticky;
    top: 0;"
                 title="工单详情">
        <router-link to="/"
                     slot="left">
          <mt-button icon="back"></mt-button>
        </router-link>
      </mt-header>
      <mt-navbar v-model="selected">
        <mt-tab-item id="1">工单处理</mt-tab-item>
        <mt-tab-item id="2">工单属性</mt-tab-item>
        <mt-tab-item id="3">工单信息</mt-tab-item>
      </mt-navbar>
      <!-- tab-container -->
      <mt-tab-container class="divs"
                        v-model="selected">
        <mt-tab-container-item id="1"
                               v-if="jsonDatas">
          <div style="display:none"
               v-if="customFormInfo.startNodeDto.nodeName">
            <node-form :jsonData="customFormInfo.startNodeDto.nodeContent"
                       @sendmsg="getMsgs"
                       ref="startForm">
            </node-form>
          </div>
          <div v-if='!(customFormInfo.contrOptionTag == 2 || customFormInfo.contrOptionTag == 0)'>
            <node-form :jsonData="jsonDatas"
                       @sendmsg="getMsg"
                       ref="mychild"></node-form>
          </div>
          <div v-if="customFormInfo.currentNodeDto.sequenceFlows">
            <mt-button style='margin:0 5px'
                       v-for="(item, index) in customFormInfo.currentNodeDto.sequenceFlows"
                       v-if="item.type=='end' || item.type=='tiaozhuan' || item.type=='save'"
                       :key="index"
                       type="primary"
                       size="small"
                       @click="changeFlows(item)">{{ item.name }}</mt-button>
          </div>
          <mt-cell class='no_data_tip'
                   v-else>暂无可处理的信息</mt-cell>
          <mt-cell title="签到地址："
                   v-if='addressShow'
                   :value="addressInfo"></mt-cell>
          <mt-button class="el_button"
                     type="primary"
                     @click.native="attendFun()">签到</mt-button>
        </mt-tab-container-item>
        <mt-tab-container-item id="2"
                               class="order_attribute">
          <mt-cell title="编号："
                   :value="customFormInfo.id"></mt-cell>
          <mt-cell title="状态："
                   :value="customFormInfo.statusName"></mt-cell>
          <mt-cell title="当前节点："
                   :value="customFormInfo.currentWorkOrderNodeName"></mt-cell>
          <mt-cell title="当前处理人："
                   :value="customFormInfo.currentHandlerName"></mt-cell>
          <mt-cell title="创建人："
                   :value="customFormInfo.createUserName"></mt-cell>
          <mt-cell title="创建时间："
                   :value="customFormInfo.createTime"></mt-cell>
          <mt-cell title="签到地址："></mt-cell>
          <p v-html="customFormInfo.signInAddress || ''"></p>
          <!-- <el-form :model="customFormInfo"
                 label-width="97px">

          <el-form-item label="编号：">{{customFormInfo.id}}</el-form-item>
          <el-form-item label="状态：">{{customFormInfo.statusName}}</el-form-item>
          <el-form-item label="当前节点：">{{customFormInfo.currentWorkOrderNodeName}}</el-form-item>
          <el-form-item label="当前处理人：">{{customFormInfo.currentHandlerName}}</el-form-item>
          <el-form-item label="创建人：">{{customFormInfo.createUserName}}</el-form-item>
          <el-form-item label="创建时间：">{{customFormInfo.createTime}}</el-form-item>
        </el-form> -->
        </mt-tab-container-item>
        <mt-tab-container-item id="3"
                               disabled='true'>
          <!-- <mt-cell class="node_name"
                 title='基础数据'></mt-cell> -->
          <div class='display:flex'>
            <mt-cell title="客户姓名："
                     :value="customFormInfo.clientName"></mt-cell>
            <mt-cell title="客户电话："
                     :value="customFormInfo.phone"></mt-cell>
            <mt-cell title="信息等级："
                     :value="customFormInfo.customField && customFormInfo.customField.msgGrade?customFormInfo.customField.msgGrade :'无'"></mt-cell>
            <mt-cell title="产品型号："
                     :value="customFormInfo.customField && customFormInfo.customField.productModel ? customFormInfo.customField.productModel : '无'"></mt-cell>
            <mt-cell title="产品大类："
                     :value="customFormInfo.customField && customFormInfo.customField.productClass?customFormInfo.customField.productClass : '无'"></mt-cell>
            <mt-cell title="责任单位："
                     :value="customFormInfo.companyName || '无'"></mt-cell>
            <mt-cell title="业务来源："
                     :value="customFormInfo.source || '无'"></mt-cell>
            <mt-cell title="优先级："
                     :value="customFormInfo.priority || '无'"></mt-cell>
            <mt-cell title="回电时间："
                     :value="customFormInfo.customField && customFormInfo.customField.subCallTime ? timestampToTime(customFormInfo.customField.subCallTime) : '无'"></mt-cell>
            <mt-cell title="类型："
                     :value="customFormInfo.workOrderTypeName"></mt-cell>
            <mt-cell title="概述："
                     :value="customFormInfo.title || '无'"></mt-cell>
          </div>
          <div v-if='customFormInfo && customFormInfo.startNodeDto'>
            <mt-cell class="node_name"
                     :title="customFormInfo.startNodeDto.nodeName"></mt-cell>
            <node-form :jsonData="customFormInfo.startNodeDto.nodeContent"
                       @sendmsg="getMsgs">
            </node-form>
          </div>
          <div v-for="(item, index) in this.customFormInfo
            .processedWorkOrderNodeDtoList"
               :key="index">
            <mt-cell class="node_name"
                     :title="item.nodeName"></mt-cell>
            <node-form :jsonData="item.nodeContent"
                       @sendmsg="getMsg"></node-form>
          </div>
        </mt-tab-container-item>
      </mt-tab-container>
    </div>
  </div>
</template>

<script>
// import BMap from "BMap"
// import { MP } from '@/assets/js/map.js'
import { Toast, MessageBox } from 'mint-ui'
import { getProcessMessage, processWorkOrder } from '@/api/orderListController'
import { addOrUpdateTaskSignIn, getTaskSignInByProcessInstanceId } from '@/api/taskSignInController'
import nodeForm from '@/components/common/nodeForm'
import common from '@/common/common.js'
export default {
  components: {
    nodeForm
  },
  data () {
    return {
      customField: {},
      addressShow: 'false',
      selected: '1',
      customFormInfo: {},
      getStartJsonData: {},
      jsonDatas: '',
      latAndLngInfo: '', // 经纬度
      addressInfo: '', // 地址
      getQianId: '', // 是否签到的id
      opration: '', // 按钮信息
      idInfo: ''
    }
  },
  created () {
    this.getDetails()
  },
  mounted () {
    // this.$nextTick(() => {
    //   const _this = this
    //   MP(_this.ak).then(BMap => {
    //     _this.getPosition()
    //   })
    // })
    this.getPosition()
  },
  computed: {
  },
  methods: {
    // 时间戳转换
    timestampToTime (timestamp) {
      if (!timestamp) {
        return
      }
      return common.timestampToTime(timestamp)
    },
    // 获取判断是否二次签到
    // getTaskSignInByProcessInstanceId () {
    //   getTaskSignInByProcessInstanceId(this.customFormInfo.processInstanceId).then(res => {
    //     let data = res.data
    //     if (data.retCode === 200) {
    //       this.getQianId = data.data
    //     }
    //   })
    // },
    // 获取当前位置
    getPosition () {
      var _this = this
      // let geolocation = new BMap.Geolocation()
      // geolocation.getCurrentPosition(function (r) {
      //   if (this.getStatus() === BMAP_STATUS_SUCCESS) {
      //     let mk = new BMap.Marker(r.point)
      //     let gc = new BMap.Geocoder()
      //     gc.getLocation(r.point, function (rs) {
      //       let addComp = rs.addressComponents
      //       let address = addComp.province + addComp.city + addComp.district + addComp.street + addComp.streetNumber // 获取地址
      //       _this.latAndLngInfo = r.point.lng + ',' + r.point.lat
      //       _this.addressInfo = address
      //     })
      //   } else {
      //     alert('failed' + this.getStatus())
      //   }
      // })
      var map = new BMap.Map("allmap");
      var point = new BMap.Point(108.95, 34.27);
      map.centerAndZoom(point, 12);
      let geolocation = new BMap.Geolocation();
      geolocation.getCurrentPosition(function (r) {
        console.log(r.point)
        if (this.getStatus() == BMAP_STATUS_SUCCESS) {
          let mk = new BMap.Marker(r.point);
          map.addOverlay(mk);//标出所在地
          map.panTo(r.point);//地图中心移动
          //alert('您的位置：'+r.point.lng+','+r.point.lat);
          let point = new BMap.Point(r.point.lng, r.point.lat);//用所定位的经纬度查找所在地省市街道等信息
          let gc = new BMap.Geocoder();
          gc.getLocation(point, function (rs) {
            _this.latAndLngInfo = rs.point.lng + ',' + rs.point.lat
            _this.addressInfo = rs.address
            // var addComp = rs.addressComponents; console.log(rs.address);//地址信息
            // alert(rs.address);//弹出所在地址
          });
        } else {
          // alert('failed' + this.getStatus());
        }
      }, { enableHighAccuracy: true })
      _this.addressShow = true
    },
    // 签到
    attendFun () {
      // this.getPosition()
      var params = {
        id: '', // 创建签到时不需要传，覆盖签到信息时需要传
        longitudeLatitude: this.latAndLngInfo, // 经纬度
        signInAddress: this.addressInfo, // 签到详细地址
        signInUserId: this.$store.state.userId, // 用户id
        processInstanceId: this.customFormInfo.processInstanceId, // 流程实例id
        workOrderId: this.customFormInfo.id // 工单id
      }
      // 处理重复签到
      if (this.getQianId) {
        params.id = this.getQianId.id
        MessageBox.confirm('重复签到会覆盖上一次的信息').then(action => {
          this.addOrUpdateTaskSignIn(params)
        })
      } else {
        delete params.id
        this.addOrUpdateTaskSignIn(params)
      }
    },
    // 签到接口
    addOrUpdateTaskSignIn (params) {
      addOrUpdateTaskSignIn(params).then(res => {
        let data = res.data
        if (data.retCode === 200) {
          Toast({
            message: '签到成功',
            iconClass: 'icon icon-success'
          })
          this.getDetails()
        } else {
          let instance = Toast(data.msg)
          setTimeout(() => {
            instance.close()
          }, 1000)
        }
      })
    },
    // 模板信息
    getMsg (data) {
      this.getJsonData = data
    },
    // 初始节点获取表单数据
    getMsgs (data) {
      this.getStartJsonData = data
    },
    // 工单详情数据
    getDetails () {
      // 开发调试数据使用
      // let resInfo = JSON.parse('{"retCode":200,"msg":null,"data":{"id":"20200407015","alterFormTag":0,"title":"","statusId":19,"createUserId":"eurmAdmin","workOrderTypeId":1586225821655,"workOrderTypeName":"测试0417","priority":"一般","clientName":"测试0407","source":"","problemDesc":"","processedWorkOrderNodeDtoList":[],"startNodeDto":{"taskId":"20033","nodeId":1586225821656,"nodeName":"新建工单","handlerId":"eurmAdmin","handlerName":"内管业务管理员","submitTime":"2020-04-07 16:15:28","nodeContent":{"list":[{"id":8,"key":"1586247328174","icon":"icon-input","name":"单行文本","type":"input","model":"input_1586247328174","rules":[{"type":"string","message":"单行文本格式不正确"}],"options":{"width":"100%","hidden":false,"pattern":"","dataBind":true,"dataType":"string","disabled":false,"required":false,"labelWidth":100,"remoteFunc":"func_1584092836349","customClass":"","placeholder":"","defaultValue":"","isLabelWidth":false,"showPassword":false},"useStatus":null,"remoteFunc":"func_1586247328174"}],"config":{"size":"small","labelWidth":100,"labelPosition":"top"}}},"currentNodeDto":{"nodeId":1586225795776,"nodeName":"新建节点1","taskId":"123TaskId","formTemplate":{"list":[{"id":8,"key":"1584092836349","icon":"icon-input","name":"单行文本","type":"input","model":"input_1584092836349","rules":[{"type":"string","message":"单行文本格式不正确"}],"options":{"width":"100%","hidden":false,"pattern":"","dataBind":true,"dataType":"string","disabled":false,"required":false,"labelWidth":100,"remoteFunc":"func_1584092836349","customClass":"","placeholder":"","defaultValue":"","isLabelWidth":false,"showPassword":false},"useStatus":null}],"config":{"size":"small","labelWidth":100,"labelPosition":"top"}},"sequenceFlows":[{"id":1586247259066,"name":"跳转","type":"tiaozhuan","uuid":1586247259066,"status":"23","sourceRef":1586225795776,"targetRef":"1586247263311"}]},"phone":"13214134343","createUserCode":"eurmAdmin","voiceKeyId":"","statusName":"工单处理中","currentWorkOrderNodeName":"新建节点1","currentHandlerName":"内管业务管理员,系统管理员","createUserName":"内管业务管理员","createTime":"2020-04-07 16:15:28","concatWorkOrderIdStr":"20200407016,20200407017","contrOptionTag":1,"currentHandlerId":"eurmAdmin,systemManager","processInstanceId":"20028","externalFlowInfo":null,"distributionWay":null,"combineWorkOrderInfo":null,"isMonitor":null,"iswithdraw":"Y","customField":{"productModel":"","productClass":"","dutyUnit":"","msgGrade":"C"},"customIdentify":"13214134343","businessHandlerId":null,"businessHandlerName":null,"signInAddress":"上海市上海市静安区天潼路619号","isViewFollowUpButton":"Y","companyName":null},"count":null,"url":null}')
      // this.customFormInfo = resInfo.data
      // this.startJsonDatas = this.customFormInfo.currentNodeDto.formTemplate
      // this.jsonDatas = this.customFormInfo.currentNodeDto.formTemplate
      // if (this.customFormInfo.processInstanceId) {
      //   // this.getTaskSignInByProcessInstanceId()
      // }
      // end
      let params = {
        id: this.$store.state.orderDetailsId,
        userId: this.$store.state.userId
      }
      getProcessMessage(params).then(res => {
        this.customFormInfo = res.data.data
        this.startJsonDatas = this.customFormInfo.currentNodeDto.formTemplate
        this.jsonDatas = this.customFormInfo.currentNodeDto.formTemplate
        this.customField = this.customFormInfo.customField
        // if (this.customFormInfo.processInstanceId) {
        //   this.getTaskSignInByProcessInstanceId()
        // }
      })
    },
    // 流程按钮
    changeFlows (val) {
      this.opration = val
      this.submitForm()
    },
    // 流程动作提交的信息
    async submitForm () {
      await this.$refs.mychild.change()
      if (this.$refs.startForm) {
        await this.$refs.startForm.change()
      }
      let params = {
        customIdentify: this.customFormInfo.customIdentify || '',
        userId: this.$store.state.userId, // 坐席工号
        workOrderTypeId: this.customFormInfo.workOrderTypeId || '', // 工单流程
        priority: this.customFormInfo.priority || '', // 工单优先级
        source: this.customFormInfo.source || '', // 工单来源
        clientName: this.customFormInfo.clientName || '', // 客户姓名
        sex: this.customFormInfo.sex || '', // 客户性别
        title: this.customFormInfo.title || '',
        phone: this.customFormInfo.phone || '', // 来电号码
        problemDesc: this.customFormInfo.problemDesc || '', // 工单内容
        workOrderId: this.customFormInfo.id, // 工单号
        tag: this.customFormInfo.alterFormTag,
        // 初始模板
        startFormInputDto: {
          content: this.getStartJsonData.content,
          modelValue: this.getStartJsonData.modelValue,
          nodeId: this.customFormInfo.startNodeDto.nodeId,
          nodeName: this.customFormInfo.startNodeDto.nodeName,
          taskId: this.customFormInfo.startNodeDto.taskId
        },
        // 当前编辑模板
        writeFormTemplateInputDto: {
          content: this.getJsonData.content,
          modelValue: this.getJsonData.modelValue,
          nodeId: this.customFormInfo.currentNodeDto.nodeId,
          nodeName: this.customFormInfo.currentNodeDto.nodeName,
          taskId: this.customFormInfo.currentNodeDto.taskId
        },
        opration: this.opration,
        redeploy: {
          roleType: '用户',
          targetNodeId: '',
          value: []
        },
        customField: this.customFormInfo.customField
      }
      processWorkOrder(params).then(res => {
        if (res.data.retCode === 200) {
          this.$message({
            message: res.data.msg,
            type: 'success'
          })
          this.$router.push({
            path: '/'
          })

          // this.getDetails()
        }
      })
    }
  }
}
</script>

<style scoped>
.divs {
  margin: 10px auto 0;
  width: 90%;
  text-align: left;
}
>>> .mint-navbar {
  background-color: #eff0f4;
}
>>> .mint-tab-item-label {
  font-size: 14px;
  font-weight: 600;
}
.el_button {
  width: 100%;
  margin: 5px 0;
  font-weight: 100;
}
.el_button >>> label {
  font-weight: 100;
  font-size: 14px;
}
.order_attribute {
  white-space: nowrap;
}
.node_name >>> .mint-cell-wrapper {
  font-weight: 600;
  padding: 0;
}
.no_data_tip {
  width: 100%;
  height: 100px;
  line-height: 100px;
  background-color: #eff0f4;
  text-align: center;
}
>>> .el-form-item__label {
  text-align: left;
}
>>> .el-button--primary {
  background-color: #26a2ff;
}
</style>
